package com.chunuo.aclservice.filter;

import com.chunuo.aclservice.security.TokenManager;
import com.chunuo.commonutils.R;
import com.chunuo.commonutils.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 访问过滤器
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenAuthenticationFilter(AuthenticationManager authManager, TokenManager tokenManager,RedisTemplate redisTemplate) {
        super(authManager);
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 当访问含有admin的路径时，获取用户的权限认证，并存到SecurityContextHolder中
     *      * @param req
     *      * @param res
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        logger.info("请求路径 ======= "+req.getRequestURI());
        //拦截路径中，没有包含admin则放行
//        if(req.getRequestURI().indexOf("admin") != -1) {
//            System.out.println("路径包含admin直接放行。。。");
//            chain.doFilter(req, res);
//            return;
//        }
        UsernamePasswordAuthenticationToken authentication = null;
        try {
            //获取用户权限认证
            authentication = getAuthentication(req);
        } catch (Exception e) {
            ResponseUtil.out(res, R.error().code(50014).message("获取用户权限认证异常"));
            return;
        }

        //如果认证的信息存在，则将其存到SecurityContextHolder中
        if (authentication != null) {
            SecurityContextHolder.getContext().setAuthentication(authentication);
        } else {
            //否则抛异常
            ResponseUtil.out(res, R.error().code(50014).message("认证权限不存在"));
            return;
        }
        //最后放行
        chain.doFilter(req, res);
    }

    /**
     * 用户权限认证
     * @param request
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // token置于header里
        String token = request.getHeader("token");
        System.out.println("token === "+token);
        if (token != null && !"".equals(token.trim())) {
            //如果请求头中token不是空的，则获取该token的用户名
            String userName = tokenManager.getUserFromToken(token);

            //从redis中获取用户权限信息
            List<String> permissionValueList = (List<String>) redisTemplate.opsForValue().get(userName);

            //存储已授权的权限
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            //遍历权限
            for(String permissionValue : permissionValueList) {
                //是空的则跳过
                if(StringUtils.isEmpty(permissionValue)) continue;
                //已授权的权限
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
                authorities.add(authority);
            }

            //如果获取的用户名不为null，则需要认证用户信息
            if (!StringUtils.isEmpty(userName)) {
                /**
                 * userName 用户名
                 * token token值
                 * authorities 已授权的权限
                 */
                return new UsernamePasswordAuthenticationToken(userName, token, authorities);
            }
            return null;
        }
        return null;
    }
}